package com.sgb.kjwl.view.ui.activity.self.packers;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AtSelfOfferMaterialEditBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.self.SelfTeamOfferEntity;
import com.sgb.kjwl.view.ui.activity.PhotoViewActivity;
import com.sgb.link.view.adapter.SelfTeamPicAdapter;
import com.sgb.kjwl.viewmodel.self.packers.SelfOfferMaterialEditModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.MToast;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

/**
 * @author liwei
 * @date 2021/1/7
 * description:添加或编辑辅材
 */
public class SelfOfferMaterialEditActivity extends AppActivity {

    @Inject
    SelfOfferMaterialEditModel viewModel;

    private AtSelfOfferMaterialEditBinding binding;

    private SelfTeamOfferEntity.MaterialListDTO mEntity;

    private SelfTeamPicAdapter mPicAdapter;
    private List<String> mUploadImgList;
    /**
     * 防止重复上传
     */
    private Map<String, String> mCacheImgMap;
    private int mCurPicNum;

    public static void start(AppActivity context, SelfTeamOfferEntity.MaterialListDTO entity, int position, int code) {
        Intent intent = new Intent(context, SelfOfferMaterialEditActivity.class);
        intent.putExtra("materialListDTO", entity);
        intent.putExtra("position", position);
        context.startActivityForResult(intent, code);
    }

    @Override
    protected boolean statusBarDark() {
        return false;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder()
                .appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mEntity == null) {
            mActionBar.setTitle("添加辅材");
            mEntity = new SelfTeamOfferEntity.MaterialListDTO();
        } else {
            mActionBar.setTitle("编辑辅材");
        }
    }

    @Override
    protected void initView() {
        mEntity = (SelfTeamOfferEntity.MaterialListDTO) getIntent().getSerializableExtra("materialListDTO");
        binding = DataBindingUtil.setContentView(this, R.layout.at_self_offer_material_edit);
        binding.setViewModel(null);
        binding.btnRelease.setOnClickListener(this);
        binding.etNum.getContent_edt().setInputType(InputType.TYPE_CLASS_NUMBER);
        initPic();
    }

    @Override
    protected void init() {
        binding.setViewModel(mEntity);
        if (mEntity != null && !TextUtils.isEmpty(mEntity.getUrl())) {
            List<String> stringList = new ArrayList<>();
            stringList.add(mEntity.getUrl());
            mPicAdapter.setData(stringList);
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_release) {
            if (TextUtils.isEmpty(binding.etMaterialsName.getContent())) {
                MToast.showToast(this, binding.etMaterialsName.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etSpecification.getContent())) {
                MToast.showToast(this, binding.etSpecification.getContent_edt().getHint().toString());
                return;
            }
            if (TextUtils.isEmpty(binding.etUnit.getContent())) {
                MToast.showToast(this, binding.etUnit.getContent_edt().getHint().toString());
                return;
            }
            mEntity.setName(binding.etMaterialsName.getContent());
            mEntity.setCategory(binding.etType.getContent());
            mEntity.setModel(binding.etSpecification.getContent());
            mEntity.setUnit(binding.etUnit.getContent());
            mEntity.setQuantity(binding.etNum.getContent());
            mUploadImgList.clear();
            mCurPicNum = -1;
            uploadPic();
        }
    }

    private void initPic() {
        mCacheImgMap = new HashMap<>();
        mUploadImgList = new ArrayList<>();
        GridLayoutManager manager = new GridLayoutManager(this, 3);
        binding.rvPic.setLayoutManager(manager);
        mPicAdapter = new SelfTeamPicAdapter(this, new ArrayList<>(), 1, manager);
        binding.rvPic.setHasFixedSize(false);
        binding.rvPic.setAdapter(mPicAdapter);
        mPicAdapter.setOnItemClick(new AdapterOnItemClick<String>() {
            @Override
            public void onItemClick(String s, int position) {
                if (TextUtils.isEmpty(s)) {
                    viewModel.pictureSelector(mPicAdapter.hasCount(), PictureConfig.CHOOSE_REQUEST);
                } else {
                    Intent intent = new Intent(getActivity(), PhotoViewActivity.class);
                    intent.putExtra(PhotoViewActivity.KEY_PHOTO_URLS, (Serializable) mPicAdapter.getDatas());
                    intent.putExtra(PhotoViewActivity.KEY_PHOTO_POSITION, position);
                    startActivity(intent);
                }
            }
        });
    }

    private void uploadPic() {
        mCurPicNum++;
        int size = mPicAdapter.getRealCount();
        if (size > 0 && mCurPicNum < size) {
            String path = mPicAdapter.getDatas().get(mCurPicNum);
            if (path.startsWith("http")) {
                mUploadImgList.add(path);
                uploadPic();
            } else {
                // 过滤已上传的
                if (!TextUtils.isEmpty(mCacheImgMap.get(path))) {
                    mUploadImgList.add(mCacheImgMap.get(path));
                    uploadPic();
                } else {
                    File file = new File(mPicAdapter.getDatas().get(mCurPicNum));
                    viewModel.uploadMultiFileModel(file, mCurPicNum + 1, size);
                }
            }
        } else {
            release();
        }
    }

    /**
     * 图片上传回调
     * @param fromString 图片本地地址
     * @param toString 图片上传后的网络地址
     */
    public void uploadPicInfo(String fromString, String toString) {
        mUploadImgList.add(toString);
        mCacheImgMap.put(fromString, toString);
        uploadPic();
    }

    private void release() {
        if (mUploadImgList.size() > 0) {
            mEntity.setUrl(mUploadImgList.get(0));
        }else {
            mEntity.setUrl("");
        }
        Intent intent = new Intent();
        intent.putExtra("material", mEntity);
        intent.putExtra("position", getIntent().getIntExtra("position", -1));
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                mPicAdapter.setPicData(selectList);
            }
        }
    }
}
